<template>
  <view class="container">
    <!-- 搜索栏 -->
    <view class="search-section">
      <input 
        class="search-input" 
        v-model="searchKeyword"
        placeholder="搜索小区/地址" 
        placeholder-style="color: #999;"
        @input="handleSearchInput"
        @confirm="handleSearchConfirm"
      />
      <button class="search-btn" @click="handleSearch">搜索</button>
    </view>

    <!-- 房屋列表 -->
    <view class="house-list">
      <view 
        v-for="house in houseList" 
        :key="house.id" 
        class="house-card"
        @click="viewDetail(house)"
      >
        <image :src="house.imgUrl" class="house-image" mode="aspectFill"></image>
        <view class="house-info">
          <view class="title-row">
            <text class="title">{{ house.title }}</text>
            <view class="status-tag" :class="{ 'status-rented': house.status === '1' }">
              {{ house.status === '0' ? '在租' : '已租' }}
            </view>
          </view>
          
          <view class="location">
            <text class="location-text">{{ formatAddress(house.address) }}</text>
          </view>
          
          <view class="details">
            <text class="detail-item">{{ house.area }}㎡</text>
            <text class="divider">|</text>
            <text class="detail-item">{{ house.bedrooms }}室{{ house.livingrooms }}厅</text>
          </view>
          
          <view class="tags">
            <text 
              v-for="(tag, index) in getTags(house)" 
              :key="index" 
              class="tag"
            >{{ tag }}</text>
          </view>
          
          <view class="bottom-row">
            <text class="price">¥{{ house.rent }}/月</text>
            <button 
              class="action-btn"
              :class="{ 'btn-disabled': house.status === '1' }"
              @click.stop="handleReserve(house)"
            >
              {{ house.status === '0' ? '预约看房' : '已出租' }}
            </button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { listHouses } from '@/api/homestay';

export default {
  data() {
    return {
      searchKeyword: '',
      houseList: [],
      loading: false,
      searchTimer: null,
    };
  },
  async created() {
    await this.fetchHouses();
  },
  methods: {
    // 防抖处理搜索
    handleSearchInput() {
      if (this.searchTimer) {
        clearTimeout(this.searchTimer);
      }
      this.searchTimer = setTimeout(() => {
        this.fetchHouses();
      }, 500);
    },

    // 处理搜索按钮点击
    async handleSearch() {
      if (this.loading) return;
      await this.fetchHouses();
    },

    // 处理回车搜索
    handleSearchConfirm() {
      this.handleSearch();
    },

    async fetchHouses() {
  if (this.loading) return;

  try {
    this.loading = true;
    const params = {
      pageNum: 1,
      pageSize: 20,
    };

    const res = await listHouses(params); // 不传 keyword，获取全部数据

    if (res.code === 200) {
      let filteredList = res.rows;

      // 如果有关键词，做本地过滤
      if (this.searchKeyword) {
        const keyword = this.searchKeyword.toLowerCase().trim();
        filteredList = res.rows.filter(house =>
          house.title.toLowerCase().includes(keyword) ||
          house.address.toLowerCase().includes(keyword)
        );
      }

      this.houseList = filteredList.map(item => ({
        ...item,
        imgUrl: item.imgUrl ? 
          (item.imgUrl.startsWith('http') ? item.imgUrl : `http://localhost:8888${item.imgUrl}`)
          : 'https://via.placeholder.com/300x200'
      }));
    } else {
      uni.showToast({ title: res.msg || '获取房屋列表失败', icon: 'none' });
    }
  } catch (error) {
    console.error('获取房屋列表失败', error);
    uni.showToast({ title: '加载失败，请重试', icon: 'none' });
  } finally {
    this.loading = false;
  }
},
 getTags(house) {
      const tags = ['住宅'];
      if (house.status === '1') tags.push('已租');
      if (house.bedrooms >= 3) tags.push('大户型');
      if (house.hasVR) tags.push('VR看房');
      return tags;
    },
    formatAddress(address) {
      if (!address) return '未知区域';
      const districts = address.split(' ').filter((item, idx, arr) => item !== arr[idx + 1]);
      return districts.slice(0, 4).join(' ');
    },
    viewDetail(house) {
      uni.navigateTo({
        url: `/pages/house-detail?id=${house.id}`
      });
    },
    handleReserve(house) {
      if (house.status === '1') {
        uni.showToast({ title: '该房源已出租', icon: 'none' });
        return;
      }
    
      uni.navigateTo({
        url: `/pages/service/reserve?id=${house.id}`
      });
    }
  }
};
</script>

<style scoped>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 30rpx;
}

/* 搜索栏样式 */
.search-section {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background-color: #fff;
  position: sticky;
  top: 0;
  z-index: 1;
}

.search-input {
  flex: 1;
  height: 72rpx;
  background: #f5f5f5;
  border-radius: 36rpx;
  padding: 0 30rpx;
  font-size: 28rpx;
}

.search-btn {
  margin-left: 20rpx;
  width: 120rpx;
  height: 72rpx;
  line-height: 72rpx;
  text-align: center;
  background: #4B7BFF;
  color: #fff;
  border-radius: 36rpx;
  font-size: 28rpx;
}

/* 房屋列表样式 */
.house-list {
  padding: 20rpx;
}

.house-card {
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.house-image {
  width: 100%;
  height: 360rpx;
  background-color: #f5f5f5;
}

.house-info {
  padding: 24rpx;
}

.title-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}

.title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  flex: 1;
  margin-right: 20rpx;
}

.status-tag {
  font-size: 24rpx;
  padding: 4rpx 16rpx;
  border-radius: 20rpx;
  background: #4B7BFF;
  color: #fff;
}

.status-tag.status-rented {
  background: #999;
}

.location {
  margin-bottom: 16rpx;
}

.location-text {
  font-size: 26rpx;
  color: #666;
}

.details {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
}

.detail-item {
  font-size: 26rpx;
  color: #666;
}

.divider {
  margin: 0 16rpx;
  color: #ddd;
}

.tags {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 20rpx;
}

.tag {
  font-size: 24rpx;
  color: #4B7BFF;
  background: rgba(75, 123, 255, 0.1);
  padding: 4rpx 16rpx;
  border-radius: 20rpx;
  margin-right: 16rpx;
  margin-bottom: 12rpx;
}

.bottom-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20rpx;
  padding-top: 20rpx;
  border-top: 1rpx solid #eee;
}

.price {
  font-size: 36rpx;
  font-weight: bold;
  color: #FF5722;
}

.action-btn {
  width: 160rpx;
  height: 64rpx;
  line-height: 64rpx;
  text-align: center;
  background: #4B7BFF;
  color: #fff;
  border-radius: 32rpx;
  font-size: 26rpx;
}

.btn-disabled {
  background: #ccc;
}
</style>